/*
 * Copyright (c) 2019-2029, <a href="https://wwww.intellijboy.cn">https://wwww.intellijboy.cn</a> (liuburu@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * <a href="https://www.apache.org/licenses/LICENSE-2.0">https://www.apache.org/licenses/LICENSE-2.0</a>
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package open.intellijboy.core.jackson;


import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import open.intellijboy.core.jackson.entity.Apple;
import open.intellijboy.core.jackson.entity.Banana;
import open.intellijboy.core.jackson.entity.IFruit;

import java.io.IOException;

/**
 * 反序列IFruit
 *
 * @author intellijboy
 * @date 2023/10/3
 * @since 1.0
 */
public class IFruitDeserializer extends JsonDeserializer<IFruit> {


    @Override
    public IFruit deserialize(JsonParser jsonParser, DeserializationContext ctx) throws IOException, JacksonException {
        ObjectMapper objectMapper = (ObjectMapper) jsonParser.getCodec();
        JsonNode node = objectMapper.readTree(jsonParser);
        String type = node.get("type").asText();
        if ("apple".equals(type)) {
            return Apple.builder()
                    .appId(node.get("appId").asInt())
                    .appName(node.get("appName").asText())
                    .build();
        } else if ("banana".equals(type)) {
            return Banana.builder()
                    .bananaId(node.get("bananaId").asText())
                    .bananaName(node.get("bananaName").asText())
                    .build();
        }

        throw new IllegalArgumentException("Unknown type: " + type);
    }
}
